#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/24 21:38
# @Author : 闫峰
# @File    : check_shoplistingsyc.py
from common.setting import ensure_path_sep
from third_services.shopee.shop.shop import Interface_shop
from utils.mysqlUtils.db_pool import Database
from utils.logging_tool.log_control import ERROR,WARNING,INFO
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg

ceshi_log = Database(ensure_path_sep("\\config\\ceshi_mysql_config.yaml"), "log_db")


class TestCheckShoplistingSyc:
    """
    获取非全球产品的在线listing数，比对平台api在线数和本地数据库数量
    """
    db = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "java_database")
    db_product = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "HWY-ZH-GZ-RDS-Product")
    ding = DingTalkSendMsg('shopee_auto')
    def test_check_shoplisting_syc(self):
        sql1 = """SELECT id,order_source_name,order_source_country FROM `zhcxkj-center-data`.rb_order_source WHERE customer_id=1  AND order_source_type=97 AND is_active=1 AND is_delete=0 AND order_source_country != 'CN';"""
        source_id_list = self.db.fetch_all(sql1, ())
        print(f"验证的渠道数{len(source_id_list)}")
        count_num = 0
        for i in source_id_list:
            res = Interface_shop().api_v2_product_get_item_list(i['id'], 1)
            count_num += 1
            print(f"验证了{count_num}个")
            if res.get('error') == "":
                OrderSourceId = i['id']
                order_source_name = i['order_source_name']
                order_source_country = i['order_source_country']
                if "】" not in order_source_name:
                    api_count = res.get("response").get("total_count")
                    sql2 = """SELECT count(*) AS num FROM `zhcxkj-center-product`.t_shopee_listing WHERE source_id=%s AND `status`=1 AND is_deleted=0;"""
                    res2 = self.db_product.fetch_all(sql2, (i['id'],))
                    PublishNum = res2[0]['num']
                    sql3 = """
                    REPLACE INTO `znkdceshilog`.sys_marketlisting_count 
                    (OrderSourceType, OrderSourceId, OrderSourceCountry, LogisticType, UserId, Quota, ApiNum, PublishNum, CreatorId, Creator, CreationTime, LastModifierId, LastModifier, LastModificationTime, order_source_name)
                    VALUES 
                    (97, %s, %s, '', '', '', %s, %s, 1, 'Admin', NOW(), 2, 'Manager', NOW(), %s);
                                """
                    res = ceshi_log.execute(sql3,
                                            (OrderSourceId, order_source_country, api_count, PublishNum, order_source_name))
                    if res == 1:
                        pass
                    elif res==2:
                        WARNING.logger.warning(f"{i}更新")
                    else:
                        WARNING.logger.warning(f"插入失败 {i}")
                else:
                    continue
            else:
                print(f"渠道id {i['id']} 名称： {i['order_source_name']} 报错信息是 {res}")
                continue



    def get_ding(self):
        res_t = ""
        res_t += "——————————————  \n"
        res_t += "|渠道id  |渠道名称|api在线数|本地在线数|        \n" \
                 "|:--------:|:-----:|:------:|:----:|  \n"
        sql4 = """SELECT OrderSourceId,order_source_name,ApiNum, PublishNum FROM znkdceshilog.sys_marketlisting_count WHERE ApiNum!=PublishNum  ORDER BY (ApiNum-PublishNum) DESC  ;"""
        res4 = ceshi_log.fetch_all(sql4,())
        for i in res4:
            res_t += f" |{i['OrderSourceId']}  | {i['order_source_name']} | {i['ApiNum']} | {i['PublishNum']} |  \n"
        self.ding.send_success(text=res_t,title='Shopeev2店铺listing监控(建议PC端查看，格式适应于PC端)',phone_list=[18118758151])


if __name__ == '__main__':
    # sql4 = """delete from `znkdceshilog`.sys_marketlisting_count;"""
    # ceshi_log.execute(sql4, ())
    TestCheckShoplistingSyc().test_check_shoplisting_syc()


